package api

import (
	"Comments/pkg/db/postgresql"
	"encoding/json"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"strconv"
)

type API struct {
	R  *mux.Router
	db *postgresql.Store
}

type tree struct {
	parentCom postgresql.Comment
	children  []tree
}

func New(db *postgresql.Store) *API {
	api := API{
		db: db,
	}
	api.R = mux.NewRouter()
	api.endpoints()
	return &api
}

func (api *API) endpoints() {
	api.R.HandleFunc("/{news_id}/comments", api.commentsByNewsIdHandler).Methods("GET")
	api.R.HandleFunc("/{news_id}/add_comments", api.addCommentHandler).Methods("POST")
}

func (api *API) Router() *mux.Router {
	return api.R
}

func (api *API) commentsByNewsIdHandler(w http.ResponseWriter, r *http.Request) {
	newsIdStr := mux.Vars(r)["news_id"]
	newsId, err := strconv.Atoi(newsIdStr)
	if err != nil {
		log.Println(err)
	}
	comments, err := api.db.CommentsByNewsId(newsId)
	if err != nil {
		log.Println(err)
	}

}
func (api *API) addCommentHandler(w http.ResponseWriter, r *http.Request) {
	newsId := mux.Vars(r)["news_id"]
	var comment postgresql.Comment
	err := json.NewDecoder(r.Body).Decode(&comment)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
	}
	comment.NewsId, err = strconv.Atoi(newsId)
	if err != nil {
		log.Println(err)
	}
	err = api.db.AddComment(comment)
	if err != nil {
		log.Println(err)
	}
	w.WriteHeader(http.StatusOK)
}

func flatArrToTree(arr []postgresql.Comment) []postgresql.Comment {
	var comTree []tree
	for _, comment := range arr {
		if comment.ParentId == 0 {
			comTree = append(comTree, tree{
				parentCom: comment,
				children:  []tree{},
			})
		}
	}
}
